package org.example.chm;/*
 * title:
 * author:
 * date:
 * description:
 * */

import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.html.HtmlParser;
import org.apache.tika.parser.microsoft.chm.ChmParser;
import org.apache.tika.sax.ToXMLContentHandler;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ChmParserWithTitles {
    public static void main(String[] args) {
        String chmFilePath = "C:\\Users\\11924\\Java\\supportSearch\\BTS3900&BTS5900 V100R019C10SPC210 Reference-CN\\性能指标参考\\BTS3900&BTS5900 V100R019C10SPC210 性能指标参考.chm";

        try (FileInputStream inputStream = new FileInputStream(new File(chmFilePath))) {
            Tika tika = new Tika();
            AutoDetectParser chmParser = new AutoDetectParser();
            ToXMLContentHandler handler = new ToXMLContentHandler();
            Metadata metadata = new Metadata();
            ParseContext parseContext = new ParseContext();

            chmParser.parse(inputStream, handler, metadata, parseContext);

            // 将提取的内容转换为XML格式，然后使用jsoup进行解析
            String htmlContent = handler.toString();
            Document doc = Jsoup.parse(htmlContent);

            // 获取所有标题（假设标题在 h1, h2, h3 等标签中）
            Elements titles = doc.select("h1, h2, h3");

            for (Element title : titles) {
                System.out.println("Title: " + title.text());
                // 输出该标题下直到下一个标题之前的所有内容
                Element sibling = title.nextElementSibling();
                while (sibling != null && !(sibling.tagName().equals("h1") || sibling.tagName().equals("h2") || sibling.tagName().equals("h3"))) {
                    System.out.println(sibling.text());
                    sibling = sibling.nextElementSibling();
                }
                System.out.println("--------------------------");
            }
        } catch (IOException | TikaException | SAXException e) {
            e.printStackTrace();
        }
    }
}
